<template>
  <div>
    <!--    面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域   -->
    <el-card>
      <!--      提示文本-->
      <el-alert
          title="添加商品信息"
          type="info"
          center
          :closable="false"
          show-icon>
      </el-alert>
      <!--      步骤条-->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!--      左侧标签页-->
      <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
          label-position="top"
      >
        <el-tabs
            v-model="activeIndex"
            :tab-position="'left'"
            :before-leave="beforeTabLeave"
            @tab-click="handleTabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_name">
              <el-cascader

                  v-model="addForm.goods_cat"
                  :options="cateList"
                  :props="cateProps"
                  clearable
                  @change="handleChange"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item of manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="cb" v-for="(cb,i) of item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
                v-for="item of onlyTableData"
                :key="item.attr_id"
                :label="item.attr_name"

            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :headers="headersObj"
                :on-success="handleSuccess"
                list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!--   定义富文本编辑器-->
            <quill-editor
                v-model="addForm.goods_introduce"
            ></quill-editor>
            <!--  添加商品按钮-->
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!--    预览图片对话框-->
    <el-dialog
        title="图片预览"
        :visible.sync="preViewDialogVisible"
        width="50%"
    >
      <img :src="preViewPath" alt="" style="width: 100%">

    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash"

export default {
  name: "Add",
  data() {
    return {
      activeIndex: '0',
      //添加商品的对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类数组,及级联选择器所选中的值
        goods_cat: [],
        // 上传图片的数组
        pics: [],
        // 商品详情描述
        goods_introduce: '',
        // 商品的参数 包含动态参数和静态属性
        attrs: []
      },
      // 添加商品表单的验证规则
      addFormRules: {
        goods_name: [
          {required: true, message: '请填写商品名称', trigger: 'blur'}
        ],
        goods_price: [
          {required: true, message: '请填写商品价格', trigger: 'blur'}
        ],
        goods_weight: [
          {required: true, message: '请填写商品重量', trigger: 'blur'}
        ],
        goods_number: [
          {required: true, message: '请填写商品数量', trigger: 'blur'}
        ]
      },
      // 指定级联选择器的对象
      cateProps: {
        expandTrigger: 'hover',
        checkStrictly: true,
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      cateList: [],
      // 动态参数
      manyTableData: [],
      // 静态属性
      onlyTableData: [],
      // 上传图片的url地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 请求头对象
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片的路径
      preViewPath: '',
      // 预览图片对话框的显示隐藏
      preViewDialogVisible: false


    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 商品分类id
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
  methods: {
    // 获取商品分类
    async getCateList() {
      const {data: res} = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.cateList = res.data
      console.log('this.cateList', this.cateList)
    },
    // 级联选择器选中项发生变化触发的事件
    handleChange() {
      console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 切换标签页的回调
    beforeTabLeave(activeName, oldActiveName) {
      console.log('即将离开的标签页', oldActiveName)
      console.log('即将进入的标签页', activeName)
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }

    },
    // 处理标签页的点击事件
    async handleTabClick() {
      console.log(this.activeIndex)
      // 获取的是动态属性
      if (this.activeIndex === '1') {
        const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        res.data.forEach(item => {
          if (item.attr_vals) {
            item.attr_vals = item.attr_vals.split(' ')
          } else {
            item.attr_vals = []
          }
        })
        this.manyTableData = res.data

        console.log('manyTable', this.manyTableData)
      } else if (this.activeIndex === '2') {
        // 获取的是静态属性
        const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.onlyTableData = res.data
        console.log('onlyTable', this.onlyTableData)
      }
    },
    // 处理图片预览的事件
    handlePreview(file) {
      console.log(file)
      this.preViewPath = file.response.data.url
      this.preViewDialogVisible = true

    },
    // 处理移除图片的事件
    handleRemove(file) {
      console.log('删了', file)
      // 获取图片的临时路径
      const filePath = file.response.data.tmp_path
      // 从pics数组中找出图片对应的索引
      const i = this.addForm.pics.findIndex(item => {
        return item.pic === filePath
      })

      // 通过调用splice方法删除数组的某一项
      this.addForm.pics.splice(i, 1)


    },
    // 处理图片上传成功
    handleSuccess(response) {
      console.log('response', response)

      // 图片信息对象
      const picInfo = {pic: response.data.tmp_path}
      // 将图片对象添加到pics数组中
      this.addForm.pics.push(picInfo)

      console.log(this.addForm)


    },
    // 添加商品
    add() {
      // 添加商品的表单预验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的表单项')

        // this.addForm.goods_cat = this.addForm.goods_cat.join(','):直接这样子拼接会报错
        // 使用lodash的cloneDeep(obj)的方法来进行对象的深拷贝
        const formObj = _.cloneDeep(this.addForm)
        // 把goods_cat数组拼接成字符串
        formObj.goods_cat = formObj.goods_cat.join(',')
        // 处理动态参数(attr_value是数组需要将其转换为字符串)

        console.log('many', this.manyTableData)
        console.log('only', this.onlyTableData)

        this.manyTableData.forEach(item => {
          console.log('item', item)
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性(attr_value本身就是字符串)
        this.onlyTableData.forEach(item => {
          const newInfo = {attr_id: item.attr_id, attr_value: item.attr_vals}
          this.addForm.attrs.push(newInfo)
        })
        // 必须要有这个赋值语句,因为只有执行了添加商品才会深拷贝对象
        formObj.attrs = this.addForm.attrs
        console.log('formObj', formObj)
        // 发起添加商品的请求
        const {data:res} = await this.$http.post('goods',formObj)
        if(res.meta.status !==201){
          return  this.$message.error(res.meta.msg)
        }
        this.$message.success('添加商品成功')
        // 跳转到商品列表
        this.$router.push('/goods')

      })


    }

  }
}
</script>

<style lang="less" scoped>
.el-tabs {
  margin-top: 15px;
}

.el-checkbox {
  margin: 0 10px 0 0 !important;
}

.el-button {
  margin-top: 15px;
}
</style>
